<?php


require_once(dirname(__FILE__).'/../../common/log.php');
require_once(dirname(__FILE__).'/../../common/defines.php');
require_once(dirname(__FILE__).'/../../common/return.php');

require_once(dirname(__FILE__).'/../common.php');


function make_umid($senderId, $recverId)
{
    //消息id
    return date('YmdHis').mt_rand(100, 999).$senderId;
}

function get_current_kefu($redis, $userId)
{
    $kefuId  = USERID_SERVER;

    do
    {
        $ret  = $redis->hget("server:current", $userId);
        if (empty($ret))
        {
            $ret  = $redis->zrangebyscore("server:online", '-inf', '+inf', ['limit' => [0, 1]]);
            if (empty($ret))
            {
                //发送短信通知
                $info['content']  = '客服消息待处理';
                $ret  = HttpUtils::send_post_request('http://localhost/sms/notice.php', [], $info);

                break;
            }
            else
            {
                $kefuId  = $ret[0];
            }

            $ret  = $redis->hsetnx("server:current", $userId, $kefuId);
        }
        else
        {
            $kefuId  = $ret;
        }
    } while (empty($ret));

    return $kefuId;
}

function recv_other_message($mysql, $userId, $kefuId)
{
    //获取该用户尚未被其他客服回复的消息，重新发送给当前客服
    $msgs  = $mysql->select('kefu_message_info', '*', "(senderId = $userId) AND (recverId != $kefuId) AND (status = 0)");
    foreach ($msgs as $msg)
    {
        send_kmsg_message($userId, [(int)$kefuId], $msg['type'], 0, json_decode($msg['content']), 1, $msg['umid'], $msg['createTime']);
    }

    if (empty($msgs))
    {
        return 0;
    }

    //将重新发送的用户消息的接收者更改为当前客服
    $ret  = $mysql->update('kefu_message_info', ['recverId' => $kefuId], "(senderId = $userId) AND (recverId != $kefuId) AND (status = 0)");
    if (($ret === FAILURE) || ($ret != count($msgs)))
    {
        loge("update kefu_message_info failed: ".json_encode(['userId' => $userId, 'kefuId' => $kefuId, 'msgs' => $msgs]));
    }

    return count($msgs);
}

function save_message($mysql, $senderId, $recverId, $type, $content, $status, $umid)
{
    //将当前消息存入数据库
    $info['createTime']  = time();
    $info['senderId']    = $senderId;
    $info['recverId']    = $recverId;
    $info['type']        = $type;
    $info['umid']        = $umid;
    $info['content']     = $content;
    $info['status']      = $status;
    $ret  = $mysql->insert('kefu_message_info', $info);
    if ($ret === FAILURE)
    {
        loge("insert kefu_message_info failed: ".json_encode($info));

        failure(ERR_SYSTEM);
    }
}
